package com.example.demo.mapper;

import com.example.demo.entity.Assignment;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface AssignmentMapper {

    // 插入作业
    @Insert("INSERT INTO assignment (course_id, description, total_score, deadline, created_at, updated_at) " +
            "VALUES (#{courseId}, #{description}, #{totalScore}, #{deadline}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Assignment assignment);

    // 根据ID查询作业
    @Select("SELECT * FROM assignment WHERE id = #{id}")
    @Results({
            @Result(column = "course_id", property = "courseId"),
            @Result(column = "total_score", property = "totalScore"),
            @Result(column = "created_at", property = "createdAt"),
            @Result(column = "updated_at", property = "updatedAt")
    })
    Assignment selectById(Long id);

    // 根据课程ID查询作业列表
    @Select("SELECT * FROM assignment WHERE course_id = #{courseId} ORDER BY deadline ASC")
    @Results({
            @Result(column = "course_id", property = "courseId"),
            @Result(column = "total_score", property = "totalScore"),
            @Result(column = "created_at", property = "createdAt"),
            @Result(column = "updated_at", property = "updatedAt")
    })
    List<Assignment> selectByCourseId(Long courseId);

    // 查询所有作业
    @Select("SELECT * FROM assignment ORDER BY created_at DESC")
    @Results({
            @Result(column = "course_id", property = "courseId"),
            @Result(column = "total_score", property = "totalScore"),
            @Result(column = "created_at", property = "createdAt"),
            @Result(column = "updated_at", property = "updatedAt")
    })
    List<Assignment> selectAll();

    // 更新作业
    @Update("UPDATE assignment SET " +
            "course_id = #{courseId}, " +
            "description = #{description}, " +
            "total_score = #{totalScore}, " +
            "deadline = #{deadline}, " +
            "updated_at = NOW() " +
            "WHERE id = #{id}")
    int update(Assignment assignment);

    // 根据ID删除作业
    @Delete("DELETE FROM assignment WHERE id = #{id}")
    int deleteById(Long id);

    // 根据课程ID删除作业
    @Delete("DELETE FROM assignment WHERE course_id = #{courseId}")
    int deleteByCourseId(Long courseId);

    // 查询截止时间前的作业
    @Select("SELECT * FROM assignment WHERE deadline > NOW() ORDER BY deadline ASC")
    @Results({
            @Result(column = "course_id", property = "courseId"),
            @Result(column = "total_score", property = "totalScore"),
            @Result(column = "created_at", property = "createdAt"),
            @Result(column = "updated_at", property = "updatedAt")
    })
    List<Assignment> selectActiveAssignments();

    // 统计课程作业数量
    @Select("SELECT COUNT(*) FROM assignment WHERE course_id = #{courseId}")
    int countByCourseId(Long courseId);
}